package com.demo.websocket.controller;

import com.demo.websocket.client.FeignClient;
import com.demo.websocket.domain.Dept;
import com.demo.websocket.domain.DoctorInfo;
import com.demo.websocket.service.DoctorService;
import com.demo.websocket.service.MedicalKnowledgeService;
import com.demo.websocket.service.PythonAIService;
import com.demo.websocket.vo.AIAnalysisResponse;
import com.demo.websocket.vo.EnhancedMedicalResponse;
import com.demo.websocket.vo.SymptomRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/medical")
@Slf4j
public class MedicalController {
    
    @Autowired
    private PythonAIService pythonAIService;
    
    @Autowired
    private MedicalKnowledgeService medicalKnowledgeService;
    
    @Autowired
    private DoctorService doctorService;

    @Autowired
    private FeignClient feignClient;
    
    @PostMapping("/triage")
    public ResponseEntity<?> medicalTriage(@RequestBody SymptomRequest request) {
        try {
            log.info("收到症状分析请求: {}", request.getSymptoms());
            
            // 1. 调用Python AI服务
            AIAnalysisResponse aiResponse = feignClient.analyzeSymptoms(request);
            log.info("AI服务返回结果: {}", aiResponse);


            // 2. 智能科室推荐（您之前需要的功能）
            Dept deptRecommendation = medicalKnowledgeService.recommendBestDepartment(aiResponse);
            
            // 3. 获取推荐医生
            List<DoctorInfo> recommendedDoctors = doctorService.findDoctorsByDepartment(
                deptRecommendation.getId(),
                aiResponse.getPossibleConditions()
            );
            
            // 4. 构建完整响应
            EnhancedMedicalResponse response = buildEnhancedResponse(
                aiResponse, deptRecommendation, recommendedDoctors);
            
            return ResponseEntity.ok(response);
            
        } catch (RuntimeException e) {
            log.error("医疗分诊处理失败: {}", e.getMessage());
            return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE)
                    .body(new HashMap<String, String>() {{
                        put("error", "分析服务暂时不可用");
                        put("message", "请稍后重试");
                        put("emergencyAdvice", "如有紧急情况请直接拨打急救电话");
                    }});

        }
    }
    
    @GetMapping("/health")
    public ResponseEntity<Map<String, Object>> healthCheck() {
        boolean pythonServiceHealthy = pythonAIService.isPythonServiceHealthy();
        
        Map<String, Object> healthInfo = new HashMap<>();
        healthInfo.put("status", pythonServiceHealthy ? "UP" : "DOWN");
        healthInfo.put("pythonService", pythonServiceHealthy ? "连接正常" : "连接失败");
        healthInfo.put("timestamp", LocalDateTime.now());
        
        HttpStatus status = pythonServiceHealthy ? HttpStatus.OK : HttpStatus.SERVICE_UNAVAILABLE;
        return ResponseEntity.status(status).body(healthInfo);
    }
    
    private EnhancedMedicalResponse buildEnhancedResponse(
            AIAnalysisResponse aiResponse,
            Dept deptRecommendation,
            List<DoctorInfo> recommendedDoctors) {
        
        EnhancedMedicalResponse response = new EnhancedMedicalResponse();
        // 复制AI响应的基础字段
        response.setSymptomAnalysis(aiResponse.getSymptomAnalysis());
        response.setPossibleConditions(aiResponse.getPossibleConditions());
        response.setUrgencyLevel(aiResponse.getUrgencyLevel());
        response.setMedicalAdvice(aiResponse.getMedicalAdvice());
        response.setRecommendedDepartment(aiResponse.getRecommendedDepartment());
        response.setWarningSigns(aiResponse.getWarningSigns());
        
        // 设置增强字段
        response.setFinalDepartment(deptRecommendation.getDeptName());
        response.setDepartmentReason(deptRecommendation.getDescription());// 此处需要根据实际需求进行修改
        response.setRecommendedDoctors(recommendedDoctors);
        response.setAvailableDoctorsCount(recommendedDoctors.size());
        
        return response;
    }
}